package com.hhkj.study.admin.order.service.biz.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.hhkj.study.admin.course.entity.Course;
import com.hhkj.study.admin.course.service.base.CourseService;
import com.hhkj.study.admin.goods.model.podo.GoodsPo;
import com.hhkj.study.admin.goods.model.podo.GoodsSkuPo;
import com.hhkj.study.admin.goods.service.base.GoodsService;
import com.hhkj.study.admin.goods.service.base.GoodsSkuService;
import com.hhkj.study.admin.order.entity.OrderItem;
import com.hhkj.study.admin.order.enums.OrderStatusEnum;
import com.hhkj.study.admin.order.model.podo.OrderItemDo;
import com.hhkj.study.admin.order.model.podo.OrderItemPo;
import com.hhkj.study.admin.order.model.req.OrderItemReq;
import com.hhkj.study.admin.order.model.res.OrderItemRes;
import com.hhkj.study.admin.order.service.base.OrderItemService;
import com.hhkj.study.admin.order.service.biz.OrderItemBizService;
import com.hhkj.study.admin.order.service.extend.OrderItemExtendService;
import com.hhkj.study.admin.user.entity.User;
import com.hhkj.study.admin.user.model.podo.UserPo;
import com.hhkj.study.admin.user.model.req.UserReq;
import com.hhkj.study.admin.user.service.base.UserService;
import com.hhkj.study.admin.user.service.biz.UserBizService;
import com.hhkj.study.common.cache.GlobalCache;
import com.ruoyi.common.base.biz.service.biz.BaseBizServiceImpl;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.DictCodeEnum;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* OrderItemBizServiceImpl
*
* @author SERVER
* @since 2024-09-18
*/
@Service
public class OrderItemBizServiceImpl extends BaseBizServiceImpl<OrderItem, OrderItemReq, OrderItemRes, OrderItemDo, OrderItemPo, OrderItemService, OrderItemExtendService> implements OrderItemBizService {

    @Resource
    private UserBizService userBizService;

    @Resource
    private GoodsService goodsService;

    @Resource
    private GoodsSkuService goodsSkuService;

    @Resource
    private OrderItemService orderItemService;

    @Resource
    private CourseService courseService;

    @Resource
    private GlobalCache globalCache;

    @Resource
    private UserService userService;


    @Override
    public List<OrderItem> saveBatchAndAssignUser(Long orderId, List<OrderItemPo> itemList) {
        for (OrderItemPo orderItem : itemList) {
            orderItem.setOrderId(orderId);
            String mobile = orderItem.getBuyerMobile();
            UserReq userReq = new UserReq();
            userReq.setMobile(mobile);
            UserPo userPo = userBizService.get(userReq);
            GoodsSkuPo goodsSkuPo = goodsSkuService.getPoById(orderItem.getGoodsSkuId());
            Long userId = 0L;
            if (userPo == null) {
                GoodsPo goodsPo = goodsService.getPoById(goodsSkuPo.getGoodsId());
                userReq.setIntentionalExamId(goodsPo.getCategoryId());
                userReq.setName(orderItem.getBuyerName());
                userBizService.save(userReq);
                userId = userReq.getId();
            }else{
                // 学员如果没有姓名,默认数据是以zjwk开头，则更新姓名
                if (StrUtil.contains(userPo.getName(), Constants.DEFAULT_USER_PREFIX)
                        && StrUtil.isNotBlank(orderItem.getBuyerName())) {
                    userService.update(Wrappers.<User>lambdaUpdate().eq(User::getId, userPo.getId())
                            .set(User::getName, orderItem.getBuyerName()));
                }
                userId = userPo.getId();
            }
            orderItem.setBuyerId(userId);
            orderItem.setStatus(OrderStatusEnum.PAID.getCode());
            orderItem.setGoodsId(goodsSkuPo.getGoodsId());
            orderItem.setGoodsSkuName(goodsSkuPo.getName());
            orderItem.setCourseIdList(goodsSkuPo.getCourseIdList());
        }

        List<OrderItem> orderItemList = new ArrayList<>();
        for (OrderItemPo orderItemPo : itemList) {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyBeanProp(orderItem, orderItemPo);
            orderItemList.add(orderItem);
        }

        orderItemService.saveBatch(orderItemList);
        return orderItemList;
    }

    @Override
    public PageInfo<OrderItemRes> paging(OrderItemReq orderItemReq) {
        // 如果有课程名称，则需要查询课程名称对应的课程id
        if (StrUtil.isNotBlank(orderItemReq.getCourseName())) {
            LambdaQueryWrapper<Course> courseQueryWrapper = Wrappers.<Course>lambdaQuery()
                    .select(Course::getId, Course::getName)
                    .like(Course::getName, orderItemReq.getCourseName());
            List<Course> courseList = courseService.list(courseQueryWrapper);
            if (CollectionUtil.isEmpty(courseList)) {
                return new PageInfo<>(new ArrayList<>());
            }
            List<Long> courseIdList = courseList.stream().map(Course::getId).collect(Collectors.toList());
            orderItemReq.setCourseIdListStr(JSONUtil.toJsonStr(courseIdList));
        }
        return super.paging(orderItemReq);
    }

    @Override
    protected void afterList(List<OrderItemRes> orderItemResList) {
        Map<Long, String> dictMap = globalCache.cacheSimpleDictMap(Lists.newArrayList(DictCodeEnum.COURSE_TYPE.getCode()));
        orderItemResList.forEach(orderItemRes -> orderItemRes.setGoodCategoryName(dictMap.get(orderItemRes.getGoodCategoryId())));
    }
}
